package com.study.cloud.gateway.client.autoConfiguration;

import com.study.cloud.gateway.client.core.ApiProperties;
import com.study.cloud.gateway.client.support.dubbo.DubboClientRegisterManager;
import com.study.cloud.gateway.client.support.springmvc.SpringMVCClientRegisterManager;
import jakarta.servlet.Servlet;
import org.apache.dubbo.config.spring.ServiceBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author wangwancheng
 * @create 2025/7/19 20:24
 */
@Configuration
@EnableConfigurationProperties(ApiProperties.class)
@ConditionalOnProperty(prefix = "api",name =  {"registerAddress"})
public class ApiClientAutoConfiguration {

    @Autowired
    private ApiProperties apiProperties;

    /**
     * 创建SpringMVCClientRegisterManager
     * 当检测到存在Servlet DispatcherServlet WebMvcConfigurer时，则系统自动创建SpringMVCClientRegisterManager
     * 当检测存在SpringMVCClientRegisterManager 时，则不创建 (手动自己创建SpringMVCClientRegisterManager)
     * @return
     */
    @Bean
    @ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
    @ConditionalOnMissingBean({SpringMVCClientRegisterManager.class})
    public SpringMVCClientRegisterManager springMVCClientRegisterManager(){
        return new SpringMVCClientRegisterManager(apiProperties);
    }


    /**
     * 创建DubboClientRegisterManager
     * 当检测到存在ServiceBean时，则系统自动创建DubboClientRegisterManager
     * ServiceBean 时dubboBean
     * 当检测存在DubboClientRegisterManager 时，则不创建 (手动自己创建DubboClientRegisterManager)
     * @return
     */
    @Bean
    @ConditionalOnClass({ServiceBean.class})
    @ConditionalOnMissingBean({DubboClientRegisterManager.class})
    public DubboClientRegisterManager dubboClientRegisterManager(){
        return new DubboClientRegisterManager(apiProperties);
    }
}
